package com.elm_springboot_s.filter;

import com.elm_springboot_s.utils.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import io.jsonwebtoken.Claims;

import java.io.IOException;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final StringRedisTemplate redisTemplate;

    public JwtAuthenticationFilter(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
                                  FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");

        // 对登录和注册请求直接放行
        if (request.getRequestURI().contains("/user/login") ||
            request.getRequestURI().contains("/user/register")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 验证token
        if (token != null && redisTemplate.hasKey(token)) {
            try {
                Claims claims = JwtUtil.parseToken(token);
                Long userId = claims.get("userId", Long.class);
                String userName = claims.get("userName", String.class);
                
                // 可以将用户信息存储到ThreadLocal中
                request.setAttribute("userId", userId);
                request.setAttribute("userName", userName);
                
                filterChain.doFilter(request, response);
            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    }
}